import express from 'express'

import bodyParser from 'body-parser'
// 导入expressjwt解析token
import { expressjwt } from 'express-jwt'
import  jwtkey from './tokenkey/index.js'
import login from './router/login.js'
import stu from './router/stu.js'
import teacher from './router/teacher.js'
import major from './router/major.js'
import classrouter from './router/class.js'
import course from './router/course.js'
import room from './router/classroom.js'
import school from './router/school.js'
import person from './router/person.js'
import role from './router/role.js'
import edit from './router/edit.js'
import leave from './router/leave.js'
const app = express()
//处理json的数据格式
app.use(bodyParser.json())
//注册处理表单数据的中间件
//当extended为false时值为数组或字符串
// 当extended为true时，值可以为任意类型
app.use(bodyParser.urlencoded({extended:false}))

//排除不需要的token的路由
app.use(expressjwt({secret:jwtkey,algorithms:["HS256"]}).unless({
     path: [/^\/api\//] 
}))
//注册处理数据库操作失败的全局中间件
app.use((req,res,next)=>{
    res.dbno=(err,status=199)=>{
        res.send({
            status,
            message:err instanceof Error ? err.message :err
        })
    }
    next()
})
//处理账号不存在密码错误的中间件
app.use((req,res,next)=>{
    res.cc=(status=198,msg)=>{
        res.send({
            status,
            message:msg
        })
    }
    next()
})

// 注册tokne失效的中间件
app.use(function (err, req, res, next) {
    if (err.name === 'UnauthorizedError') {   
        //  这个需要根据自己的业务逻辑来处理（ 具体的err值 请看下面）
     return res.send({status:197,msg:'token失效'})
    }
    next()
  });

app.use('/api',login)
app.use('/stu',stu)
app.use('/teacher',teacher)
app.use('/major',major)
app.use('/class',classrouter)
app.use('/course',course)
app.use('/classroom',room)
app.use('/school',school)
app.use('/person',person)
app.use('/role',role)
app.use('/edit',edit)
app.use('/leave',leave)
app.listen(8088, () => {
    console.log('http://127.0.0.1"8088');
})